package cn.ycc1.boot3video.video;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class HlsMasterPlaylistGenerator {

//    @Data
//    public static class VariantStream {
//
//
//    }

    public static String generateMasterPlaylist2(List<VariantStreamBak> variants) {
        StringBuilder m3u8 = new StringBuilder();

        m3u8.append("#EXTM3U\n");
        m3u8.append("#EXT-X-VERSION:3\n\n");

        for (VariantStreamBak variant : variants) {
            // 关键：每个变体流必须有 BANDWIDTH 参数
            m3u8.append("#EXT-X-STREAM-INF:")
                    .append("BANDWIDTH=").append(variant.getBandwidth())
                    .append(",RESOLUTION=").append(variant.getResolution())
                    .append(",CODECS=\"").append(variant.getCodecs()).append("\"")
                    .append(",NAME=\"").append(variant.getName()).append("\"")
                    .append("\n")
                    .append(variant.getUri())  // 指向子播放列表
                    .append("\n\n");
        }

        return m3u8.toString();
    }

    public static String generateMasterPlaylist(List<VariantStreamBak> variants) {
        StringBuilder m3u8 = new StringBuilder();

        // M3U8 header
        m3u8.append("#EXTM3U\n");
        m3u8.append("#EXT-X-VERSION:3\n\n");

        // Add each variant stream
        for (VariantStreamBak variant : variants) {
            m3u8.append("#EXT-X-STREAM-INF:");
            m3u8.append("BANDWIDTH=").append(variant.getBandwidth());

            if (variant.getResolution() != null) {
                m3u8.append(",RESOLUTION=").append(variant.getResolution());
            }

            if (variant.getCodecs() != null) {
                m3u8.append(",CODECS=\"").append(variant.getCodecs()).append("\"");
            }

            if (variant.getName() != null) {
                m3u8.append(",NAME=\"").append(variant.getName()).append("\"");
            }

            m3u8.append("\n");
            m3u8.append(variant.getUri()).append("\n\n");
        }

        return m3u8.toString();
    }

    public static void saveToFile(String content, String filePath) throws IOException {
        try (FileWriter writer = new FileWriter(filePath)) {
            writer.write(content);
        }
    }

    public static void main(String[] args) {
        // 创建不同清晰度的变体流
        List<VariantStreamBak> variants = new ArrayList<>();
        variants.add(new VariantStreamBak(
                "1080p.m3u8",
                2000000,
                "1920x1080",
                "avc1.640028,mp4a.40.2",
                "1080p"
        ));
        variants.add(new VariantStreamBak(
                "720p.m3u8",
                1000000,
                "1280x720",
                "avc1.64001f,mp4a.40.2",
                "720p"
        ));
        variants.add(new VariantStreamBak(
                "480p.m3u8",
                500000,
                "854x480",
                "avc1.64001e,mp4a.40.2",
                "480p"
        ));
        variants.add(new VariantStreamBak(
                "360p.m3u8",
                250000,
                "640x360",
                "avc1.64001e,mp4a.40.2",
                "360p"
        ));

        // 生成主播放列表
        String masterPlaylist = generateMasterPlaylist(variants);
        System.out.println(masterPlaylist);

        // 保存到文件
        try {
            saveToFile(masterPlaylist, "master.m3u8");
            System.out.println("Master playlist saved to master.m3u8");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//    /**
//     * 生成主播放列表内容
//     */
//    public static String generateMasterPlaylist(List<VariantStream> variants) {
//        StringBuilder m3u8 = new StringBuilder();
//
//        // M3U8 头部
//        m3u8.append("#EXTM3U\n");
//        m3u8.append("#EXT-X-VERSION:3\n");
//        m3u8.append("\n");
//
//        // 按带宽从高到低排序（可选，但推荐）
//        variants.sort((v1, v2) -> Integer.compare(v2.getBandwidth(), v1.getBandwidth()));
//
//        // 添加每个变体流
//        for (VariantStream variant : variants) {
//            m3u8.append("#EXT-X-STREAM-INF:");
//            m3u8.append("BANDWIDTH=").append(variant.getBandwidth());
//
//            if (variant.getResolution() != null && !variant.getResolution().isEmpty()) {
//                m3u8.append(",RESOLUTION=").append(variant.getResolution());
//            }
//
//            if (variant.getCodecs() != null && !variant.getCodecs().isEmpty()) {
//                m3u8.append(",CODECS=\"").append(variant.getCodecs()).append("\"");
//            }
//
//            if (variant.getName() != null && !variant.getName().isEmpty()) {
//                m3u8.append(",NAME=\"").append(variant.getName()).append("\"");
//            }
//
//            m3u8.append("\n");
//            m3u8.append(variant.getUri()).append("\n");
//            m3u8.append("\n");
//        }
//
//        return m3u8.toString();
//    }

    /**
     * 保存主播放列表到文件
     */
    public static void saveMasterPlaylistToFile(String content, String filePath) throws IOException {
        try (FileWriter writer = new FileWriter(filePath)) {
            writer.write(content);
            System.out.println("Master playlist saved to: " + filePath);
        }
    }

    /**
     * 生成默认的多清晰度主播放列表
     */
    public static void generateMasterPlaylist(String outputDir) {
        // 创建不同清晰度的变体流配置
        List<VariantStreamBak> variants = new ArrayList<>();

        variants.add(new VariantStreamBak(
                "1080p.m3u8",
                2000000,
                "1920x1080",
                "avc1.640028,mp4a.40.2",
                "1080p"
        ));

        variants.add(new VariantStreamBak(
                "720p.m3u8",
                1000000,
                "1280x720",
                "avc1.64001f,mp4a.40.2",
                "720p"
        ));

        variants.add(new VariantStreamBak(
                "480p.m3u8",
                500000,
                "854x480",
                "avc1.64001e,mp4a.40.2",
                "480p"
        ));

        variants.add(new VariantStreamBak(
                "360p.m3u8",
                250000,
                "640x360",
                "avc1.64001e,mp4a.40.2",
                "360p"
        ));

        // 生成主播放列表内容
        String masterContent = generateMasterPlaylist(variants);

        // 保存到文件
        try {
            String masterFilePath = outputDir + "/master.m3u8";
            saveMasterPlaylistToFile(masterContent, masterFilePath);
        } catch (IOException e) {
            System.err.println("Failed to save master playlist: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 动态生成主播放列表（根据实际存在的文件）
     */
    public static void generateDynamicMasterPlaylist(String outputDir) {
        List<VariantStreamBak> variants = new ArrayList<>();

        // 检查哪些清晰度文件实际存在
        String[] qualities = {"1080p", "720p", "480p", "360p"};
        java.io.File outputFolder = new java.io.File(outputDir);

        for (String quality : qualities) {
            String playlistFile = quality + ".m3u8";
            java.io.File file = new java.io.File(outputFolder, playlistFile);

            if (file.exists()) {
                // 根据清晰度设置参数
                VariantStreamBak variant = createVariantForQuality(quality, playlistFile);
                if (variant != null) {
                    variants.add(variant);
                    System.out.println("Including quality: " + quality);
                }
            } else {
                System.out.println("Skipping missing quality: " + quality);
            }
        }

        if (variants.isEmpty()) {
            System.err.println("No quality variants found in: " + outputDir);
            return;
        }

        // 生成并保存主播放列表
        String masterContent = generateMasterPlaylist(variants);
        try {
            String masterFilePath = outputDir + "/master.m3u8";
            saveMasterPlaylistToFile(masterContent, masterFilePath);
        } catch (IOException e) {
            System.err.println("Failed to save master playlist: " + e.getMessage());
        }
    }

    /**
     * 根据清晰度创建对应的变体流配置
     */
    private static VariantStreamBak createVariantForQuality(String quality, String playlistFile) {
        switch (quality) {
            case "1080p":
                return new VariantStreamBak(playlistFile, 2000000, "1920x1080", "avc1.640028,mp4a.40.2", "1080p");
            case "720p":
                return new VariantStreamBak(playlistFile, 1000000, "1280x720", "avc1.64001f,mp4a.40.2", "720p");
            case "480p":
                return new VariantStreamBak(playlistFile, 500000, "854x480", "avc1.64001e,mp4a.40.2", "480p");
            case "360p":
                return new VariantStreamBak(playlistFile, 250000, "640x360", "avc1.64001e,mp4a.40.2", "360p");
            default:
                return null;
        }
    }

//    /**
//     * 测试方法
//     */
//    public static void main(String[] args) {
//        // 测试1: 生成默认的主播放列表
//        System.out.println("=== 测试1: 默认主播放列表 ===");
//        String testOutputDir = "/tmp/hls_output";
//        generateMasterPlaylist(testOutputDir);
//
//        // 测试2: 生成动态主播放列表
//        System.out.println("\n=== 测试2: 动态主播放列表 ===");
//        generateDynamicMasterPlaylist(testOutputDir);
//
//        // 测试3: 自定义变体流
//        System.out.println("\n=== 测试3: 自定义变体流 ===");
//        List<MasterPlaylistGenerator.VariantStream> customVariants = new ArrayList<>();
//        customVariants.add(new MasterPlaylistGenerator.VariantStream("high.m3u8", 3000000, "2560x1440", "avc1.64002a,mp4a.40.2", "2K"));
//        customVariants.add(new MasterPlaylistGenerator.VariantStream("medium.m3u8", 1500000, "1920x1080", "avc1.640028,mp4a.40.2", "1080p"));
//
//        String customContent = generateMasterPlaylist(customVariants);
//        System.out.println(customContent);
//    }

}
